package siteflash.helper;

import siteflash.model.Paginate;

public class Paginator {

	private int limit = 12;
	private int limitPage = 10;
	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getLimitPage() {
		return limitPage;
	}

	public void setLimitPage(int limitPage) {
		this.limitPage = limitPage;
	}

	public Paginate paginate(int page, int total) {
		int limit = this.limit;
		int limitPage = this.limitPage;
		Paginate paginate = new Paginate();
		paginate.setLimit(limit);
		paginate.setLimitPage(limitPage);
		//Calculator step
		int step = (int) limitPage/2;
		int rangeNextStep = limitPage - step;
		
		//Calculator total page
		int totalPage = (int) total/limit;
		if (total%limit > 0) {
			totalPage = totalPage + 1;
		}
		paginate.setTotal(totalPage);
		//Next page and preview page
		if (page == 1) {
			paginate.setNext(0);
			paginate.setPrev(0);
		}
		else if (page == totalPage) {
			paginate.setNext(0);
			paginate.setPrev(page - 1);
		}
		else if (page < totalPage) {
			paginate.setNext(page + 1);
			paginate.setPrev(page - 1);
		}
		
		if (page <= totalPage - rangeNextStep ) 
		{
			int rangePrevStep = limitPage - rangeNextStep;
			if (page - rangePrevStep < 0) {
				if (page <= totalPage - rangeNextStep + (page - rangePrevStep)) {
					paginate.setEnd(page + rangeNextStep - (page - rangePrevStep));
				} else {
					paginate.setEnd(totalPage);
				}
			} else {
				paginate.setEnd(page + rangeNextStep);
			}
		} 
		else if (page <= totalPage) 
		{
			rangeNextStep = totalPage - page;
			paginate.setEnd(totalPage);
		}
		else {
			rangeNextStep = 0;
			paginate.setEnd(page);
		}
		if (page - (limitPage - rangeNextStep) >= 1 ) 
		{
			paginate.setStart(page - (limitPage - rangeNextStep));
		} 
		else if (page >= 1) 
		{
			paginate.setStart(1);
		}
		
		paginate.setCurrentPage(page);
		
		/*System.out.println("Total Page: " + paginate.getTotal());
		System.out.println("Next Page: " + paginate.getNext());
		System.out.println("Prev Page: " + paginate.getPrev());
		System.out.println("Start Page: " + paginate.getStart());
		System.out.println("End Page: " + paginate.getEnd());
		System.out.println("Current Page: " + paginate.getCurrentPage());*/
		
		return paginate;
	}
}
